package com.jtw.udp;

import javax.swing.plaf.basic.BasicTabbedPaneUI;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

/**
 * DESCRIPT:
 *
 * @author cjsky666
 * @date 2019/4/5 16:57
 */
public class test {
    public static void main(String[] args) {
//        1 Byte = 8 Bits
//        1 KB = 1024 Bytes
//        1 MB = 1024 KB
//        1 GB = 1024 MB
        ByteBuffer byteBuffer = ByteBuffer.allocate(128);
        System.out.println(byteBuffer);
        for (int i = 0; i < 6; i++) {
            byte [] s = (i+"安徽的").getBytes();
            byteBuffer.put(s);
            System.out.println(s.length+","+byteBuffer.mark());
        }
        System.out.println(byteBuffer.remaining());
//      填充完毕之后需要反转一下。position = 0；limit =最大的有效数据长度。
//      用来说明这个缓冲区的有效数据的标识
        byteBuffer.flip();
        byte [] bytes = new byte[byteBuffer.limit()];
        do {
            byteBuffer.get(bytes);
            try {
                System.out.println(new String(bytes,"UTF-8"));
                System.out.println(byteBuffer);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }while (byteBuffer.remaining()>0);
        System.out.println(byteBuffer);
        byteBuffer.limit(byteBuffer.capacity());//重新指定一下最大可读写数据的空间
        byteBuffer.put("新增的".getBytes());//新增数据
        byteBuffer.flip();//重置可读区域
        byteBuffer.position(60);
        bytes = new byte[9];
        System.out.println("第二遍");
        System.out.println(byteBuffer);
        do {
            byteBuffer.get(bytes);
            try {
                System.out.println(new String(bytes,"UTF-8"));
                System.out.println(byteBuffer);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }while (byteBuffer.remaining()>0);
    }

}
